package com.example.yiznspringtestinterface.transaction;

import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * project : trip
 * <p> 在一个事务方法中，事务执行成功之后在调用其他服务，比如发送消息 </p>
 *
 * @author yisl
 * @date 2023-01-05【星期四】
 **/
public class TransactionUtils {

    public static void doAfterTranstion(Runnable runnable){
        if(TransactionSynchronizationManager.isActualTransactionActive()){
            TransactionSynchronizationManager.registerSynchronization(new DoTransactionCompletion(runnable));
        }
    }
}
class DoTransactionCompletion implements TransactionSynchronization{

    private Runnable runnable;
    public DoTransactionCompletion(Runnable runnable) {
        this.runnable = runnable;
    }

    @Override
    public void afterCompletion(int status) {
        if(status == TransactionSynchronization.STATUS_COMMITTED){
            this.runnable.run();
        }
    }
}
